package com.dhecp.project.logstics.service.impl;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.alibaba.fastjson.JSON;
import com.dhecp.common.core.domain.AjaxResult;
import com.dhecp.common.utils.MessageUtils;
import com.dhecp.common.utils.RandomValueUtils;
import com.dhecp.common.utils.StringUtils;
import com.dhecp.core.constant.DataFiltering;
import com.dhecp.core.enums.LogisticsType;
import com.dhecp.core.utils.PageUtils;
import com.dhecp.project.business.domain.LogisticsMmodeGrads;
import com.dhecp.project.common.service.impl.BaseModuleServiceImpl;
import com.dhecp.project.logstics.mapper.LogsticsMmodeGradsMapper;
import com.dhecp.project.logstics.service.LogisticsMmodeGradsService;
import com.dhecp.project.system.service.SysDictionaryForFieldService;

/**
 * 物流梯度 服务层
 * @Author fxz
 * @Date 2023/03/23
 */
@Service
public class LogsticsMmodeGradsServicelmpl extends BaseModuleServiceImpl implements LogisticsMmodeGradsService {


    @Autowired
    private LogsticsMmodeGradsMapper logsticsMmodeGradsMapper;

    @Autowired
    private SysDictionaryForFieldService dictionaryForFieldService;

    /**
     * 查询物流名称
     * @param params
     * @return
     * @throws Exception
     */
    @Override
    public List<LogisticsMmodeGrads> queryList(Map<String, Object> params) throws Exception {
        params.put(DataFiltering.TABLE_ALIAS, "t1");	//查询表别名
        params.put(DataFiltering.DATA_WHERE, dictionaryForFieldService.getWhereStr(params));	//常规查询条件SQL语句
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));	//数据权限查询条件SQL语句

        if (params.get("field") == null || params.get("field") == ""){
            String orderBy = "t1.startSection asc";
            PageUtils.startPageOrder(orderBy);
        }else{
            PageUtils.startPage();
        }

        return logsticsMmodeGradsMapper.findLogisticsMmodeGrads(params);
    }


    /**
     * 新增物流梯度
     * @param params
     * @return
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public AjaxResult insertLogisticsMmodeGrads(Map<String, Object> params) {
        if (StringUtils.isEmpty(params)) {
            return AjaxResult.error("数据提交失败，必填参数有误！");
        }
        List<LogisticsMmodeGrads> logisticsMmodeGradsList = JSON.parseArray(params.get("logisticsmmodegrads").toString(), LogisticsMmodeGrads.class);
        if (logisticsMmodeGradsList.size() == 0) {
            return AjaxResult.error("数据包格式有误，请检查！");
        }
        //查询所有的物流梯度区间
        Map<String, Object> params2 = new HashMap<String, Object>();
        params2.put("type",logisticsMmodeGradsList.get(0).getType());
        //获取物流方式梯度
        List<LogisticsMmodeGrads> grads = logsticsMmodeGradsMapper.findLogisticsMmodeGrads(params2);
        List<LogisticsMmodeGrads> gradsList = null;
        List<LogisticsMmodeGrads> gradsList1 = null;
        for (LogisticsMmodeGrads logisticsMmodeGrads : logisticsMmodeGradsList){
            if (logisticsMmodeGrads.getStartSection().compareTo(logisticsMmodeGrads.getEndSection()) >= 0){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error("开始值不允许小于等于结束值");
            }
            if (logisticsMmodeGrads.getType().equals(LogisticsType.JZFS.getCode())){
                gradsList = grads.stream().filter(logisticsMmodeGrads1 -> logisticsMmodeGrads.getStartSection().compareTo(logisticsMmodeGrads1.getStartSection()) >= 0
                        && logisticsMmodeGrads.getStartSection().compareTo(logisticsMmodeGrads1.getEndSection()) <= 0
                        && !logisticsMmodeGrads.getGuid().equals(logisticsMmodeGrads1.getGuid())
                        && logisticsMmodeGrads.getName().equals(logisticsMmodeGrads1.getName())
                ).collect(Collectors.toList());
                gradsList1 = grads.stream().filter(logisticsMmodeGrads1 -> logisticsMmodeGrads.getEndSection().compareTo(logisticsMmodeGrads1.getStartSection()) >= 0
                        && logisticsMmodeGrads.getEndSection().compareTo(logisticsMmodeGrads1.getEndSection()) <= 0
                        && !logisticsMmodeGrads.getGuid().equals(logisticsMmodeGrads1.getGuid())
                        && logisticsMmodeGrads.getName().equals(logisticsMmodeGrads1.getName())
                ).collect(Collectors.toList());
            } else {
                gradsList = grads.stream().filter(logisticsMmodeGrads1 -> logisticsMmodeGrads.getStartSection().compareTo(logisticsMmodeGrads1.getStartSection()) >= 0
                        && logisticsMmodeGrads.getStartSection().compareTo(logisticsMmodeGrads1.getEndSection()) <= 0
                        && !logisticsMmodeGrads.getGuid().equals(logisticsMmodeGrads1.getGuid())
                ).collect(Collectors.toList());
                gradsList1 = grads.stream().filter(logisticsMmodeGrads1 -> logisticsMmodeGrads.getEndSection().compareTo(logisticsMmodeGrads1.getStartSection()) >= 0
                        && logisticsMmodeGrads.getEndSection().compareTo(logisticsMmodeGrads1.getEndSection()) <= 0
                        && !logisticsMmodeGrads.getGuid().equals(logisticsMmodeGrads1.getGuid())
                ).collect(Collectors.toList());
            }
            if (gradsList.size() != 0 || gradsList1.size() != 0){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error("区间有重叠");
            }
        }
        for (LogisticsMmodeGrads logisticsMmodeGrads : logisticsMmodeGradsList){
            logisticsMmodeGrads.setGuid(RandomValueUtils.getGUID());
            logsticsMmodeGradsMapper.insertLogisticsMmodeGrads(logisticsMmodeGrads);
        }
        return AjaxResult.success("操作成功！");
    }


    /**
     * @Description: 查询指定单nid的首记录
     * @Param: [params]
     * @Author: fxz
     * @date: 2022-09-22 19:00
     */
    @Override
    public LogisticsMmodeGrads queryFirstByGuid(Map<String, Object> params) throws Exception {
        params.put(DataFiltering.TABLE_ALIAS, "t1");	//查询表别名
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));	//数据权限查询条件SQL语句
        return logsticsMmodeGradsMapper.queryFirstByGuid(params);
    }


    /**
     * 修改物流梯度
     * @author fxz
     * @date: 2022-09-22
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public AjaxResult updateLogisticsMmodeGrads(Map<String, Object> params) {
        if (StringUtils.isEmpty(params)) {
            return AjaxResult.error("数据提交失败，必填参数有误！");
        }
        List<LogisticsMmodeGrads> logisticsMmodeGradsList = JSON.parseArray(params.get("logisticsmmodegrads").toString(), LogisticsMmodeGrads.class);
        if (logisticsMmodeGradsList.size() == 0) {
            return AjaxResult.error("数据包格式有误，请检查！");
        }
        //查询所有的物流梯度区间
        Map<String, Object> params2 = new HashMap<String, Object>();
        params2.put("type",logisticsMmodeGradsList.get(0).getType());
        //获取物流方式梯度
        List<LogisticsMmodeGrads> grads = logsticsMmodeGradsMapper.findLogisticsMmodeGrads(params2);
        List<LogisticsMmodeGrads> gradsList;
        List<LogisticsMmodeGrads> gradsList1;
        for (LogisticsMmodeGrads logisticsMmodeGrads : logisticsMmodeGradsList){
            if (logisticsMmodeGrads.getStartSection().compareTo(logisticsMmodeGrads.getEndSection()) >= 0){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error("开始值不允许小于等于结束值");
            }
            if (logisticsMmodeGrads.getType().equals(LogisticsType.JZFS.getCode())){
                gradsList = grads.stream().filter(logisticsMmodeGrads1 -> logisticsMmodeGrads.getStartSection().compareTo(logisticsMmodeGrads1.getStartSection()) >= 0
                        && logisticsMmodeGrads.getStartSection().compareTo(logisticsMmodeGrads1.getEndSection()) <= 0
                        && !logisticsMmodeGrads.getGuid().equals(logisticsMmodeGrads1.getGuid())
                        && logisticsMmodeGrads.getName().equals(logisticsMmodeGrads1.getName())
                ).collect(Collectors.toList());
                gradsList1 = grads.stream().filter(logisticsMmodeGrads1 -> logisticsMmodeGrads.getEndSection().compareTo(logisticsMmodeGrads1.getStartSection()) >= 0
                        && logisticsMmodeGrads.getEndSection().compareTo(logisticsMmodeGrads1.getEndSection()) <= 0
                        && !logisticsMmodeGrads.getGuid().equals(logisticsMmodeGrads1.getGuid())
                        && logisticsMmodeGrads.getName().equals(logisticsMmodeGrads1.getName())
                ).collect(Collectors.toList());
            } else {
                gradsList = grads.stream().filter(logisticsMmodeGrads1 -> logisticsMmodeGrads.getStartSection().compareTo(logisticsMmodeGrads1.getStartSection()) >= 0
                        && logisticsMmodeGrads.getStartSection().compareTo(logisticsMmodeGrads1.getEndSection()) <= 0
                        && !logisticsMmodeGrads.getGuid().equals(logisticsMmodeGrads1.getGuid())
                ).collect(Collectors.toList());
                gradsList1 = grads.stream().filter(logisticsMmodeGrads1 -> logisticsMmodeGrads.getEndSection().compareTo(logisticsMmodeGrads1.getStartSection()) >= 0
                        && logisticsMmodeGrads.getEndSection().compareTo(logisticsMmodeGrads1.getEndSection()) <= 0
                        && !logisticsMmodeGrads.getGuid().equals(logisticsMmodeGrads1.getGuid())
                ).collect(Collectors.toList());
            }
            if (gradsList.size() != 0 || gradsList1.size() != 0){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error("区间有重叠");
            }
            if (logisticsMmodeGrads.getType().equals(LogisticsType.WLPMTD.getCode())){
                if (logisticsMmodeGrads.getStartSection().compareTo(new BigDecimal(100)) > 0
                        || logisticsMmodeGrads.getEndSection().compareTo(new BigDecimal(100)) > 0
                        || logisticsMmodeGrads.getKg().compareTo(new BigDecimal(100)) > 0){
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.error("开始值或者结束值或者数值,不允许超过100!");
                }
            }
        }
        for (LogisticsMmodeGrads logisticsMmodeGrads : logisticsMmodeGradsList){
            logsticsMmodeGradsMapper.updateByGuid(logisticsMmodeGrads);
        }
        return AjaxResult.success("操作成功！");

    }

    /**
     * 删除物流梯度
     * @author fxz
     * @date: 2023-03-24
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public AjaxResult deleteLogisticsMmodeGrads(Map<String, Object> params) {
        List<LogisticsMmodeGrads> logisticsMmodeGradsList = JSON.parseArray(params.get("logisticsmmodeInfoItems").toString(), LogisticsMmodeGrads.class);
        if (logisticsMmodeGradsList == null || logisticsMmodeGradsList.size() == 0) {
            return AjaxResult.error(MessageUtils.message("module.error.jsontoentyerror"));
        }
        for (LogisticsMmodeGrads logisticsMmodeGrads : logisticsMmodeGradsList) {
            logsticsMmodeGradsMapper.delete(logisticsMmodeGrads);
        }
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"));
    }

}
